﻿using System;
using System.Windows;
using System.Windows.Markup;
using Foundation.ExtensionMethods;

namespace Foundation.MarkupExtensions
{
    /// <summary>
    /// PropertyLocalizing.
    /// </summary>
    public class PropertyLocalizing :  Localizing
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyLocalizing"/> class.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        public PropertyLocalizing(string propertyName)
            : base(propertyName)
        {
        }

        /// <summary>
        /// When implemented in a derived class, returns an object that is set as the value of the target property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        /// The object value to set on the property where the extension is applied.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var service = (IProvideValueTarget) serviceProvider.GetService(typeof (IProvideValueTarget));
            var targetObject = service.TargetObject as FrameworkElement;
            if (targetObject != null)
            {
                var dependancyObject = targetObject.DataContext as DependencyObject;
                if (dependancyObject != null)
                {
                    var attachedLocalizing = dependancyObject.GetAttachedLocalizing();
                    if (attachedLocalizing != null) return attachedLocalizing.ProvideValue(serviceProvider);
                }

                var value = targetObject.DataContext != null ? targetObject.DataContext.GetPropertyValue(Key) as string ?? Key : Key;
                return ProvideValue(value, StringFormat, Transformer, Tail, targetObject, service.TargetProperty);
            }

            // This is the Clr Property case 

            // Setters, Triggers, DataTriggers & Conditions are the special cases of 
            // Clr properties where DynamicResource & Bindings are allowed. However
            // StyleHelper.ProcessSharedPropertyValue avoids a call to ProvideValue
            // in these cases and so there is no need for special code to handle them here.

            // Find the MemberType
            return this;
        }
    }
}
